package de.jmda.sample.junit;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;

import org.junit.Test;

import de.jmda.core.mproc.ProcessingUtilities;

public class TestSuiteDataBuilder
{
	private Map<PackageElement, Set<TypeElement>> typesByPackage =
	    new HashMap<PackageElement, Set<TypeElement>>();

	/**
	 * Calculates map ({@link #typesByPackage}) that contains type elements with
	 * at least one @{@link Test} annotated method per package element.
	 *
	 * @param typeElements
	 */
	public TestSuiteDataBuilder(Collection<TypeElement> typeElements)
	{
		for (TypeElement typeElement : typeElements)
		{
			PackageElement packageElement =
			    ProcessingUtilities.getPackageOf(typeElement);

			Set<TypeElement> types = typesByPackage.get(packageElement);

			if (types == null)
			{
				types = new HashSet<TypeElement>();
			}

			types.add(typeElement);
			typesByPackage.put(packageElement, types);
		}
	}

	/**
	 * Passes <code>rootDirOfFilesToProcess</code> to {@link
	 * TestProcessor#process(File)} and uses its return value to let a {@link
	 * TestSuiteDataBuilder} instance calculate the result of this method.
	 *
	 * @param rootDirOfFilesToProcess
	 * @return map that contains type elements with at least one @{@link Test}
	 *         annotated method per package element
	 */
	public static Map<PackageElement, Set<TypeElement>> build(
			File rootDirOfFilesToProcess)
	{
		TestSuiteDataBuilder builder =
				new TestSuiteDataBuilder(TestProcessor.process(rootDirOfFilesToProcess));

		return builder.typesByPackage;
	}
}